print("======================================字典的创建===============================================")

# 方式一：花括号
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(person)

# 方式二：dict() 构造函数
point = dict(x=1, y=2)
print(point)

# 方式三：从键值对列表创建
colors = dict([('r', 'red'), ('g', 'green')])
print(colors)

# 方式四：使用 dict.fromkeys()
defaults = dict.fromkeys(['host', 'port'], 'default')
print(defaults)

print("======================================通过键获取值===============================================")

person = {'name': 'Alice', 'age': 30}

print(person['name'])  # 输出: 'Alice'
# print(person['job'])      # 报错: KeyError

print(person.get('age'))  # 输出: 30
print(person.get('job'))  # 输出: None
print(person.get('job', 'unemployed'))  # 输出: 'unemployed'

print("======================================检查键是否存在===============================================")
print('age' in person)  # 输出: True
print('job' in person)  # 输出: False

print("======================================修改与更新字典===============================================")

person = {'name': 'Alice', 'age': 30}
print(person)
# 添加新键值对
person['city'] = 'London'  # 输出: {'name': 'Alice', 'age': 30, 'city': 'London'}
print(person)
# 更新现有键
person['age'] = 31  # 输出: {'name': 'Alice', 'age': 31, 'city': 'London'}
print(person)
# 使用 update()
person.update({'job': 'Engineer', 'age': 32})
print(person)
# 输出: {'name': 'Alice', 'age': 32, 'city': 'London', 'job': 'Engineer'}

print("======================================遍历字典===============================================")

person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# 遍历键
for key in person.keys():
    print(key, end="    ")  # 输出: name, age, city
print()
# 遍历值
for value in person.values():
    print(value, end="    ")  # 输出: Alice, 30, New York

print()
# 遍历键值对（推荐）
for key, value in person.items():
    print(f"{key}: {value}", end="    ")  # 输出: name: Alice, age: 30, city: New York

print()
# 直接遍历字典等价于遍历键
for key in person:
    print(key, end="    ")  # 输出: name, age, city
print()
